package com.atguigu.tingshu.payment.strategy;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;

public interface PaySubmitStrategy {

    //定义下单接口的抽象方法
    public abstract WeChatPayVo paySbumit(String paymentType, String orderNo) ;

    //获取支付类型的抽象方法
    public abstract String getPaymentType();

    public default WeChatPayVo requestJsapi(RSAAutoCertificateConfig autoCertificateConfig , Integer mount ,
                                            WxPayV3Config wxPayV3Config , String orderNo , UserInfoFeignClient userInfoFeignClient , String description) {

        // 请求微信支付平台的jsapi的下单接口，生成预支付订单
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(autoCertificateConfig).build();

        // 创建一个预支付的请求对象
        PrepayRequest prepayRequest = new PrepayRequest() ;

        Amount amount = new Amount();
        amount.setTotal(mount);                 // 订单金额，单位为分
        prepayRequest.setAmount(amount);
        prepayRequest.setAppid(wxPayV3Config.getAppid());
        prepayRequest.setMchid(wxPayV3Config.getMerchantId());
        prepayRequest.setDescription(description);
        prepayRequest.setNotifyUrl(wxPayV3Config.getNotifyUrl());
        prepayRequest.setOutTradeNo(orderNo);

        // 获取当前登录的用户
        Long userId = AuthContextHolder.getUserId();
        Result<UserInfo> userInfoResult = userInfoFeignClient.findUserInfoById(userId);
        UserInfo userInfo = userInfoResult.getData();

        Payer payer = new Payer();
        payer.setOpenid(userInfo.getWxOpenId());                  // 当前登录用户在微信支付平台上openId
        prepayRequest.setPayer(payer);            // 支付者

        // 发送支付下单请求
        PrepayWithRequestPaymentResponse prepayWithRequestPaymentResponse = service.prepayWithRequestPayment(prepayRequest);

        // 构建响应结果数据
        WeChatPayVo weChatPayVo = new WeChatPayVo() ;
        weChatPayVo.setTimeStamp(prepayWithRequestPaymentResponse.getTimeStamp());
        weChatPayVo.setNonceStr(prepayWithRequestPaymentResponse.getNonceStr());
        weChatPayVo.setPackageVal(prepayWithRequestPaymentResponse.getPackageVal());
        weChatPayVo.setSignType(prepayWithRequestPaymentResponse.getSignType());
        weChatPayVo.setPaySign(prepayWithRequestPaymentResponse.getPaySign());

        return weChatPayVo ;

    }



}
